<template>
  <div>
    <video ref="video" controls style="width: 100%; max-width: 800px;"></video>
  </div>
</template>

<script>
import Hls from 'hls.js';

export default {
  name: 'HlsPlayer',
  data () {
    return {
      videoUrl: 'http://192.168.1.225:8101/test1/test1/hls.m3u8'
    };
  },
  mounted () {
    this.initPlayer();
  },
  beforeUnmount () {
    this.destroyPlayer();
  },
  methods: {
    initPlayer () {
      if (Hls.isSupported()) {
        this.hls = new Hls();
        this.hls.loadSource(this.videoUrl);
        this.hls.attachMedia(this.$refs.video);
        this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          this.$refs.video.play();
        });
      } else if (this.$refs.video.canPlayType('application/vnd.apple.mpegurl')) {
        // 原生支持HLS的情况（如Safari）
        this.$refs.video.src = this.videoUrl;
        this.$refs.video.addEventListener('loadedmetadata', () => {
          this.$refs.video.play();
        });
      }
    },
    destroyPlayer () {
      if (this.hls) {
        this.hls.destroy();
        this.hls = null;
      }
    },
  },
};
</script>

<style scoped>
/* 可选：样式调整 */
</style>
